package com.example.cdpbookstore.web.servlet;


import com.example.cdpbookstore.constant.FilePath;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@WebServlet("/img/*")
public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String imageName = req.getPathInfo().substring(1);
        String imageName = req.getPathInfo();

        int buffSize = 1024 * 10;
        byte[] buff = new byte[buffSize];
        try (
                BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(Paths.get(FilePath.IMAGE + imageName)), buffSize);
                BufferedOutputStream bos = new BufferedOutputStream(resp.getOutputStream(), buffSize)) {
            while (bis.read(buff) != -1) {
                bos.write(buff);
                bos.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
